package com.ptu.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ptu.constant.MessageConstant;
import com.ptu.constant.PasswordConstant;
import com.ptu.constant.StatusConstant;
import com.ptu.context.BaseContext;
import com.ptu.dto.StoreDTO;
import com.ptu.dto.StoreLoginDTO;
import com.ptu.dto.StorePageQueryDTO;
import com.ptu.entity.Banner;
import com.ptu.entity.Store;
import com.ptu.exception.AccountLockedException;
import com.ptu.exception.AccountNotFoundException;
import com.ptu.exception.PasswordErrorException;
import com.ptu.mapper.BannerMapper;
import com.ptu.mapper.StoreMapper;
import com.ptu.result.PageResult;
import com.ptu.service.StoreService;
import com.ptu.vo.StoreVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private BannerMapper bannerMapper;

    /**
     * 员工登录
     *
     * @param storeLoginDTO
     * @return
     */
    public Store login(StoreLoginDTO storeLoginDTO) {
        String username = storeLoginDTO.getUsername();
        String password = storeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Store store = storeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (store == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //明文进行加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(store.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (store.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return store;
    }

    /**
     * 新增员工
     *
     * @param storeDTO
     */
    public void save(StoreDTO storeDTO) {
        System.out.println("当前线程id:" + Thread.currentThread().getId());
        Store store = new Store();
        //对象属性拷贝
        BeanUtils.copyProperties(storeDTO, store);
        //设置账号的状态，默认正常1，锁定0
        store.setStatus(StatusConstant.ENABLE);
        store.setShopstatus(StatusConstant.ENABLE);//营业状态为打烊
        store.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        store.setCreateTime(LocalDateTime.now());
        store.setUpdateTime(LocalDateTime.now());
        store.setUpdateUser(BaseContext.getCurrentId());
        storeMapper.insert(store);
    }

    /**
     * 分页查询
     *
     * @param storePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(StorePageQueryDTO storePageQueryDTO) {
        PageHelper.startPage(storePageQueryDTO.getPage(), storePageQueryDTO.getPageSize());
        Page<Store> page = storeMapper.pageQuery(storePageQueryDTO);

        long total = page.getTotal();
        List<Store> records = page.getResult();
        return new PageResult(total, records);
    }

    @Override
    public void startOrStop(Integer status, Long id) {

        Store store = Store.builder()
                .status(status)
                .id(id)
                .build();
        storeMapper.update(store);
    }

    @Override
    public void shopStatus(Integer shopstatus, Long id) {

        Store store = Store.builder()
                .shopstatus(shopstatus)
                .id(id)
                .build();
        storeMapper.update(store);
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @Override
    public StoreVO getById(Long id) {
        StoreVO storeVO = storeMapper.getById(id);
        List<Banner> banners = bannerMapper.selectByStoreId(id);
        storeVO.setBanners(banners);
        storeVO.setPassword("****");
        return storeVO;
    }

    /**
     * 编辑员工信息
     *
     * @param storeDTO
     */
    @Override
    public void update(StoreDTO storeDTO) {
        // 将 StoreDTO 的属性复制到 Store 对象
        Store store = new Store();
        BeanUtils.copyProperties(storeDTO, store);
        if (store.getPassword() != null) {
            store.setPassword(DigestUtils.md5DigestAsHex(storeDTO.getPassword().getBytes()));
            storeMapper.update(store);
        } else {
            // 获取当前店铺 ID
            Long storeId = BaseContext.getCurrentId();
            bannerMapper.deleteByStoreId(storeId);
            // 遍历 banners 列表
            List<Banner> banners = storeDTO.getBanners();
            if (banners != null) {
                for (Banner banner : banners) {
                    // 设置 url（虽然本身已有，但确保完整性）
                    if (banner.getUrl() != null) {
                        banner.setUrl(banner.getUrl());
                    }
                    // 设置 storeId
                    banner.setStoreId(storeId);
                    // 设置创建时间
                    banner.setCreateTime(LocalDateTime.now());
                    // 调用 bannerMapper 插入 banner 到数据库
                    bannerMapper.insert(banner);
                }
            }

            // 调用 storeMapper 更新员工信息
            storeMapper.update(store);
        }
    }

}
